package com.ruoyi.quartz;

import com.ruoyi.book.constants.Constants;
import com.ruoyi.book.domain.Chapter;
import com.ruoyi.book.domain.Fiction;
import com.ruoyi.book.service.IChapterService;
import com.ruoyi.book.service.IFictionService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.utils.JsoupUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("bookTask")
public class BookTask {

    private static final Logger logger = LoggerFactory.getLogger(BookTask.class);

    @Autowired
    private IFictionService fictionService;

    @Autowired
    private IChapterService chapterService;

    @Autowired
    private RedisCache redisCache;


    //抓取
    public void crawlingBook()
    {
        String fictionURL = "https://www.477zw3.com/html/253/253214/";
        //爬取小说基本信息
        Fiction fiction = JsoupUtil.getFictions(JsoupUtil.getDoc(fictionURL));
        if (fiction != null) {
            Fiction fiction1 = fictionService.selectFictionByFictionName(fiction.getFictionName());
            // 判断最新章节是否在数据库里
            Chapter chapter = chapterService.selectChapterByChapterTitle(fiction.getId(),fiction.getNewest());

            if (fiction1 == null || chapter == null) {

                if(fiction1 == null){
                    fictionService.insertFiction(fiction);
                }else{
                    fiction.setId(fiction1.getId());
                }

                Document doc = JsoupUtil.getDoc(fictionURL);
                Elements elements = doc.select(".box_con #list dl").get(1).getElementsByTag("a");
                logger.info("小说章数：" + elements.size());

                // 查询小说当前章数
                Integer size = 0;
                if(redisCache.hasKey(Constants.CHAPTER_NUM + fiction.getId())){
                    size = redisCache.getCacheObject(Constants.CHAPTER_NUM + fiction.getId());
                }else{
                    List<Chapter> chapterList = chapterService.selectChapterByFictionId(fiction.getId());
                    redisCache.setCacheObject(Constants.CHAPTER_NUM + fiction.getId(), chapterList.size());
                    size = chapterList.size();
                }

                Chapter chapterContent = new Chapter();
                chapterContent.setFictionId(fiction.getId());
                for (int i = size; i <  elements.size(); i++) {
                    try {
                        String url = "https://www.477zw3.com" + doc.select(".box_con #list dl").get(1).select("dd").get(i).select("a").attr("href");
                        Document document = JsoupUtil.getDoc(url);
                        //章节标题
                        String title = document.select(".content_read .bookname h1").text();
                        //章节内容
                        String text = document.getElementById("content").html();
                        //保存小说内容

                        text.replaceAll("Ｗωw.Ч㈦7zw.cóm", "");
                        text.replaceAll("M.④⑦七Ζw.℃om", "");
                        text.replaceAll("网站即将关闭，下载星星阅读app为您提供大神李别浪的我爹绝对被人夺舍了", "");
                        text.replaceAll("下载星星阅读app，阅读最新章节内容无广告免费", "");
                        // 去掉此内容之后的所有数据 想要看最新章节内容，请下载星星阅读app，无广告免费阅读最新章节内容。网站已经不更新最新章节内容，已经星星阅读小说APP更新最新章节内容。
                        text = text.substring(0, text.indexOf("想要看最新章节内容，请下载星星阅读app，无广告免费阅读最新章节内容。网站已经不更新最新章节内容，已经星星阅读小说APP更新最新章节内容。"));
                        chapterContent.setContent(text);
                        chapterContent.setChapterUrl(url);
                        chapterContent.setChapterTitle(title);
                        chapterContent.setSort(i + 1);
                        chapterService.insertChapter(chapterContent);
                        logger.info("抓取小说：" + fiction.getFictionName() + "" + title);
                        // 暂停两秒
                        Thread.sleep(10000);
                    } catch (Exception e) {
                        logger.error("抓取小说内容异常" + e);
                    }
                }
                logger.info("抓取小说完成");


            } else {
                logger.info("这本小说已经保存到数据库");
            }
        } else {
            logger.info("小说连接地址错误");
        }


    }




    /**
     * 获取书趣阁小说基本信息
     *
     * @param document
     * @return
     */
    public Fiction getFictions(Document document) {
        boolean flag = false;
        try {
            //小说基本信息
            String readUrl = document.select("meta[property=og:novel:read_url]").attr("content");
            String fictionName = document.select("meta[property=og:novel:book_name]").attr("content");
            String brief = document.select("meta[property=og:description]").attr("content");
            String author = document.select("meta[property=og:novel:author]").attr("content");
            String type = document.select("meta[property=og:novel:category]").attr("content");
            String newest = document.select("meta[property=og:novel:latest_chapter_name]").attr("content");
            String state = document.select("meta[property=og:novel:status]").attr("content");
             String img = document.select("#fmimg > img").attr("abs:src");
//            Elements imgElements = document.select(".container .border3-2 .info-main .lazy");
//            String img = imgElements.first().attr("data-original");
            //字数
//                String number = JsoupUtil.sub(small.get(0).child(3).text());
            return new Fiction(readUrl, img, brief, fictionName, author, type, newest, state, "");
        } catch (Exception e) {
            logger.error("获取小说基本信息失败" + e);
        }
        return null;
    }






}
